#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <ctype.h>

using namespace std;

const int base_size = 1024;
const int envnum = 64;
const int argvnum = 64;

//全局参数列表
char* gargv[argvnum];
int gargc = 0;

//全局变量,错误码
int lastcode = 0;

//我的系统环境变量
char* genv[envnum];

//当前shell的工作路径
char pwd[base_size];
//环境变量中的工作路径
char pwdenv[base_size];

//定义重定向
#define NONEREDIR 0
#define INPUTREDIR 1
#define OUTPUTREDIR 2
#define APPENDREDIR 3

//去掉空格宏函数
#define TrimSapce(pos) do{\
        while(isspace(*pos)){\
            pos++; }\
    }while(0)
//默认重定向
int redir = 0;
//文件名
char* filename = nullptr;

string GetUserName()
{
    string name = getenv("USER");
    return name.empty() ? "None" : name;
}

string GetHostName()
{
    string hostname = getenv("HOSTNAME");
    return hostname.empty() ? "None" : hostname;
}

string GetPwd()
{
    if(nullptr == getcwd(pwd,sizeof(pwd)))
        return "None";
    snprintf(pwdenv,sizeof(pwdenv),"PWD=%s",pwd);
    //修改当前路径至环境变量
    putenv(pwdenv);

    return pwd;
}

string LastDir()
{
    string curr = GetPwd();
    if(curr == "/" || curr == "None") return curr;
    size_t pos = curr.rfind("/");
    if(pos == string::npos) return curr;
    return curr.substr(pos+1);
}

string MakeCommandLine()
{
    char command_line[base_size];
    snprintf(command_line,base_size,"[%s@%s %s ]# ",\
            GetUserName().c_str(),GetHostName().c_str(),LastDir().c_str());
    return command_line;
}

void  PrintCommandLine()
{
    printf("%s",MakeCommandLine().c_str());
    fflush(stdout);

}

bool GetCommandLine(char command_buffer[],int size)
{
    char* result = fgets(command_buffer,size,stdin);
    if(!result)
    {
        return false;
    }
    //在回车位置上置为'\0'
    command_buffer[strlen(command_buffer)-1] = 0;
    if(strlen(command_buffer) == 0)
        return false;
    return true;
}

void Debug(char* command_buffer)
{
    printf("%s\n",command_buffer);
}

//重置参数列表
void RsetCommandLIine()
{
    memset(gargv,0,sizeof(gargv));
    gargc = 0;
    redir = NONEREDIR;
    filename = nullptr;
}
void ParseCommand(char* command_buffer)
{
    const char *sep = " ";
    gargv[gargc++] = strtok(command_buffer,sep);
    while((bool)(gargv[gargc++] = strtok(nullptr,sep)));
        gargc--;
}
void ParseRedir(char* command_buffer,int len)
{
    int end = len - 1;
    while(end >= 0)
    {
        if(command_buffer[end] == '<')
        {
            //输入重定向
            redir = INPUTREDIR;
            filename = &command_buffer[end] + 1;
            command_buffer[end] = 0;
            TrimSapce(filename);
            break;
        }
        else if(command_buffer[end] == '>')
        {
            if(command_buffer[end-1] == '>')
            {
                //追加重定向
                redir = APPENDREDIR;
                filename = &command_buffer[end] + 1;
                command_buffer[end] = 0;
                command_buffer[end-1] = 0;
                TrimSapce(filename);
                break;

            }
            else
            {
                //输出重定向
                
                redir = OUTPUTREDIR;
                filename = &command_buffer[end] + 1;
                command_buffer[end] = 0;
                TrimSapce(filename);
                break;
            }
        }
        else
        {
            end--;
        }
    }
}
void ParseCommandLine(char* command_buffer,int len)
{
   //重置参数列表 
    RsetCommandLIine();
    //获取重定向命令
    ParseRedir(command_buffer,len);
    //解析命令
    ParseCommand(command_buffer);
}

void DeBug()
{
    //printf("gargc :%d\n",gargc);
    for(int i = 0; genv[i]; i++)
    {
        printf("[%d]:%s\n",i,genv[i]);
    }

}
void DoRedir()
{
    if(redir == INPUTREDIR)
    {
        if(filename)
        {
            int fd = open(filename,O_RDONLY);
            if(fd < 0)
            {
                exit(2);
            }
            dup2(fd,0);
        }
        else
        {
            exit(1);
        }
    }
    else if(redir == OUTPUTREDIR)
    {

        if(filename)
        {
            int fd = open(filename,O_CREAT | O_WRONLY | O_TRUNC,0666);
            if(fd < 0)
            {
                exit(4);
            }
            dup2(fd,1);
        }
        else
        {
            exit(3);
        }
    }
    else if(redir == APPENDREDIR)
    {
        
        if(filename)
        {
            int fd = open(filename,O_CREAT | O_WRONLY | O_APPEND,0666);
            if(fd < 0)
            {
                exit(6);
            }
            dup2(fd,1);
        }
        else
        {
            exit(5);              
        }
    }

    else
    {
        //无需重定向
    }
}
void ExceCommandLine()
{
    //子进程执行命令
    
    pid_t id = fork();
    if(id < 0) return;
    if(id == 0)
    {
        //重定向执行
       DoRedir();
       execvpe(gargv[0],gargv,genv);
       exit(1);
    }
    //父进程等待
    int status = 0;
    pid_t rid = waitpid(id,&status,0);
    if(rid > 0)
    {
        if(WIFEXITED(status))
        {
            lastcode = WIFEXITED(status);
        }
        else
        {
            lastcode = 100;
        }

    }
    
}

void AddEnv(const char* item)
{
    int index = 0;
    while(genv[index])
    {
        index++;

    }
    genv[index] = (char*)malloc(strlen(item)+1);
    strncpy(genv[index],item,strlen(item)+1);
    genv[++index] = nullptr;
}
bool CheckAndBulitExecBuitCommand()
{
    if(strcmp(gargv[0],"cd") == 0)
    {
        if(gargc == 2)
        {
            chdir(gargv[1]);
            lastcode = 0;
        }
        else
        {
            lastcode = 1;
        }
        return true;
    }
    else if(strcmp(gargv[0],"export") == 0)
    {
        if(gargc == 2)
        {
            AddEnv(gargv[1]);
            lastcode = 0;
        }
        else
        {
            lastcode = 2;
        }
        return true;
    }
    
    else if(strcmp(gargv[0], "env") == 0)
    {
        for(int i = 0; genv[i]; i++)
        {
            printf("%s\n", genv[i]);
        }
        lastcode = 0;
        return true;
    }
    else if(strcmp(gargv[0], "echo") == 0)
    {
        if(gargc == 2)
        {
            // echo $?
            // echo $PATH
            // echo hello
            if(gargv[1][0] == '$')
            {
                if(gargv[1][1] == '?')
                {
                    printf("%d\n", lastcode);
                    lastcode = 0;
                }
            }
            else
            {
                printf("%s\n", gargv[1]);
                lastcode = 0;
            }
        }
        else
        {
            lastcode = 3;
        }
        return true;
    }    
     return false;
}

void InitEnv()
{
    extern char** environ;
    int index = 0;
    while(environ[index])
    {
        genv[index] = (char*)malloc(strlen(environ[index])+1);
        strncpy(genv[index],environ[index],strlen(environ[index])+1);
        index++;
    }
    genv[index] = nullptr;
}
int main()
{
    //初始化shell环境变量
    InitEnv();
    //创建接受命令行字符串数组
    char command_buffer[base_size];
    while(true)
    {

       //获取命令行提示符
       PrintCommandLine();
       //获取命令行参数
       //判断是否正确读取参数
       if(!GetCommandLine(command_buffer,base_size))
       {
           continue;
       }
       //解析指令
       ParseCommandLine(command_buffer,strlen(command_buffer));

       //执行命令
       
       if(CheckAndBulitExecBuitCommand())
       {
            continue;
       }
        ExceCommandLine();

       //执行命令
    }
    return 0;

}
















